﻿using Sustainalytics.Entities;
using System;
using System.Linq;

namespace Sustainalytics.DataLayer
{
    /// <summary>
    /// Extensions for News.
    /// </summary>
    public static class NewsExtensions
    {
        /// <summary>
        /// Filter news query.
        /// </summary>
        /// <param name="query"> News query. </param>
        /// <param name="filter"> News filter. </param>
        /// <returns> Filtered news. </returns>
        public static IQueryable<News> Filter(this IQueryable<News> query, NewsFilter filter)
        {
            if (string.IsNullOrEmpty(filter.Term) == false)
            {
                string term = filter.Term.ToLowerInvariant();

                // filter title or tags
                query = query.Where(el => el.TitleLowercase.Contains(term) || el.Tags.Any(tag => tag.NameLowercase.Contains(term)));
            }

            if (filter.Category.HasValue)
            {
                // filter by category
                query = query.Where(el => el.Category == filter.Category.Value);
            }

            if (filter.IsPublished)
            {
                query = query.Where(el => el.Status == NewsStatus.Published && el.DateCreated >= DateTime.UtcNow.AddMonths(-3) && el.UnpublishedDate > DateTime.UtcNow);
            }

            if (filter.AvailableFilter != NewsAvailability.All)
            {
                //if AvailableFilter = Client then we choose the news with the AvailableFor = Client or All
                query = query.Where(el => el.AvailableFor == filter.AvailableFilter || el.AvailableFor == NewsAvailability.All);
            }

            return query;
        }
    }
}
